var express = require('express');
var router = express.Router();
let {pets_hosp,project,part,userkjq_model,part_type_model,help_model} = require('../../models/db')

//获取商店
router.get('/pets',async(req,res)=>{
  console.log(req.query)
  var list =await pets_hosp.find()
  if(req.query.text!=''){
   list=await pets_hosp.find({name:RegExp(req.query.text)})
  }

  if(req.query.business!=0){
    list=await pets_hosp.find({name:RegExp(req.query.text),business:parseInt(req.query.business)})
    console.log(list)
  }

  if(req.query.long!=0){
    list=await pets_hosp.find({name:RegExp(req.query.text)}).sort({long:parseInt(req.query.long)})
  }

  

  var pro = await project.find()
  var newlist =[]
  list.forEach(e=>{
    var arr = []
    pro.forEach(i=>{
      if(e.host.includes(i._id)){
        arr.push(i)
      }
    })
    e.host=arr
    newlist.push(e)
  })
  res.send({list:newlist})
})


//获取兼职任务
router.get('/part',async(req,res)=>{
  var dict = {}
  if(req.query.type){
    dict.type = req.query.type
  }

  var list = await part.find(dict)
  var user = await userkjq_model.find()
  var newlist = []
  list.forEach(e=>{
    var arr=[]
    user.forEach((i)=>{
      if(e.setid.includes(i._id)){
        arr.push(i)
      }
    })
    e.setid=arr
    newlist.push(e)
  })
  res.send({list:newlist})
})

// 添加任务
router.post('/part',async(req,res)=>{
  await part.create(req.body)
  console.log(req.body)
  res.send('ok')
})

// 添加任务人数
router.post('/addpart',async(req,res)=>{
  console.log(req.body)
  var list = await part.find({_id:req.body._id})
  if(list[0].setid.includes(req.body.setid)){
    res.send('已应聘')
  }else{
    list[0].setid.push(req.body.setid)
    await part.updateOne({_id:req.body._id},list[0])
  }

  res.send('ok')
})


// 获取兼职类型
router.get('/part_type',async(req,res)=>{
  var list = await part_type_model.find()
  res.send({list:list})
})

// 获取帮助/寻宠的信息
router.get('/help',async(req,res)=>{
  var list = await help_model.find().populate('userid')
  console.log(list)
  res.send({list:list})
})


module.exports = router;
